package com.linghang.wusthelper.task;

import com.linghang.wusthelper.common.URLConst;
import com.linghang.wusthelper.dao.primary.AnnouncementDao;
import com.linghang.wusthelper.dao.primary.LibAnnouncementDao;
import com.linghang.wusthelper.spider.jwc.JwcAnnouncementSpider;
import com.linghang.wusthelper.spider.library.LibAnnouncementSpider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Spider;

import java.util.Date;


/**
 * @author origin
 * 定时任务
 */
@EnableScheduling
@Component
public class JwcScheduleTask {

    @Autowired
    private AnnouncementDao announcementDao;

    @Autowired
    private LibAnnouncementDao libAnnouncementDao;

    private Logger log = LoggerFactory.getLogger(getClass());

    /**
     * 定时爬取教务处公告
     */
    //todo  设置教务处通知公告爬取时间
    @Scheduled(cron = "0 0 2 * * ?")
    public void jwcAnnSpiderSchedule(){
        for (int i = 1; i <= 5;i++){
            Spider.create(new JwcAnnouncementSpider(announcementDao)).addUrl("http://jwc.wust.edu.cn/1925/list"+i+".htm").run();
            log.info("第"+i+"页已爬取完毕");
        }
    }

    @Scheduled(cron = "0 0 2 * * ?")
    public void libAnnSpiderSchedule(){
        Spider.create(new LibAnnouncementSpider(libAnnouncementDao)).addUrl(URLConst.LIBANNOUNCEMENTURL).run();
        log.info("图书馆公告爬取完毕");
    }

    /**
     * 定时删除陈旧的公告
     */
    @Scheduled(cron = "0 15 10 15 * ?")
    public void jwcDelete(){
        Date date = announcementDao.find70();
        announcementDao.deleteMore(date);
    }

    @Scheduled(cron = "0 15 10 15 * ?")
    public void libDelete() {
        Date date = libAnnouncementDao.find19();
        libAnnouncementDao.deleteMore(date);
    }

}
